package com.wn.class30.service.impl;

import com.wn.class30.entity.User;
import com.wn.class30.entity.Vip;
import com.wn.class30.mapper.UserDao;
import com.wn.class30.mapper.VipDao;
import com.wn.class30.service.VipService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;

@Service
@Slf4j
public class VipServiceImp implements VipService {
    @Resource
    private VipDao vipDao;
    @Resource
    private UserDao userDao;
    @Override
    /*更新用户vip等级*/
    public void updateVipLv(Integer userid) throws Exception {
        User user = userDao.selectByPrimaryKey(userid);
        if(user.getTel()!=null && user.getTel()!=""){
           List<Vip> vips = vipDao.selectByExample(null);
            vips.sort(new Comparator<Vip>() {
                @Override
                public int compare(Vip o1, Vip o2) {
                    return o1.getLvPoints()-o2.getLvPoints();
                }
            });
           User user1 = new User();
           user1.setUserId(user.getUserId());
            for(int i=0;i<vips.size();i++){
                if(user.getPoints()>vips.get(vips.size()-1).getLvPoints()){
                    user1.setLvId(vips.get(vips.size()-1).getLvId());
                            break;
                }
                if(user.getPoints()<vips.get(i).getLvPoints()){
                    user1.setLvId(vips.get(i-1).getLvId());
                    break;
                }
            }
            log.info("-------------------"+user1.getLvId());
            log.info("-------------------"+user.getLvId());
           if(user1.getLvId()!=user.getLvId()){
             userDao.updateByPrimaryKeySelective(user1);}
       }
    }
}
